package cc.wsyw126.java.nowcoder.sword_offer;

import java.util.ArrayList;

/**
 * Created by dp on 17/3/29.
 */
public class PrintMatrix {
    private ArrayList<Integer> result = new ArrayList<>();

    public ArrayList<Integer> printMatrix(int[][] matrix) {
        if (matrix == null) return result;
        int columns = matrix[0].length;
        int rows = matrix.length;
        int start = 0;
        while (start < columns / 2 + 1 || start < rows / 2 + 1) {
            doPrintMartix(matrix, columns, rows, start);
            start++;
        }
        return result;
    }

    private void doPrintMartix(int[][] matrix, int columns, int rows, int start) {
        int endX = columns - 1 - start;
        int endY = rows - 1 - start;

        for (int i = start; i <= endX; i++) {
            int number = matrix[start][i];
            result.add(number);
        }

        if (start < endY) {
            for (int i = start + 1; i <= endY; i++) {
                int number = matrix[i][endX];
                result.add(number);
            }
        }

        if (start < endX && start < endY) {
            for (int i = endX - 1; i >= start; i--) {
                int number = matrix[endY][i];
                result.add(number);
            }
        }

        if (start < endX && start < endY - 1) {
            for (int i = endY - 1; i > start; i--) {
                int number = matrix[i][start];
                result.add(number);
            }
        }
    }

    public static void main(String[] args) {
        PrintMatrix printMatrix = new PrintMatrix();
        int[][] matrix = {
                {1, 2, 3, 4},
                {5, 6, 7, 8},
                {9, 10, 11, 12}
        };
        ArrayList<Integer> arrayList = printMatrix.printMatrix(matrix);
        for (Integer integer : arrayList) {
            System.out.print(integer + "\t");
        }
        System.out.println();
    }
}
